package com.mrd.serverconnect.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.LocaleList;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextClock;
import android.widget.TextView;
import android.widget.Toast;

import com.mrd.serverconnect.DeviceWaitingSearch;
import com.mrd.serverconnect.R;
import com.mrd.serverconnect.been.LanguageBean;
import com.mrd.serverconnect.been.abs.SimpleNameValueBeanInterface;
import com.mrd.serverconnect.pkg.AuthPKGHelp;
import com.mrd.serverconnect.pkg.HeartPKGHelp;
import com.mrd.serverconnect.pkg.PKGBase;
import com.mrd.serverconnect.pkg.UpPKGHelp;
import com.mrd.serverconnect.util.DateUtil;
import com.mrd.serverconnect.util.LanguageUtil;
import com.mrd.serverconnect.util.SPUtils;
import com.mrd.serverconnect.widget.GradientColorTextView;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.mrd.serverconnect.adapter.SimpleNameValueAdapter;


public class MainActivity extends AppCompatActivity {

    /**
     * spiner相关
     */
    private TextView textView;

    //首先还是先声明这个Spinner控件
    private Spinner spinner;

    //定义一个String类型的List数组作为数据源
    private List<String> dataList;

    private List<SimpleNameValueBeanInterface> dataSource;

    //定义一个ArrayAdapter适配器作为spinner的数据适配器
    private SimpleNameValueAdapter adapter;

    /**
     * ALert相关
     */
    private AlertDialog dialog;


    private static final String TAG = "MainActivity";
    private static final long DELAY_TIME = 45000;
    private static final int DEVICE_FIND_PORT = 6090;
    private boolean isStartTimer;
    private Timer timer;
    private TextView tvTodayNum, tvMonthNum, tvYearNum, tvTotalNum, tvInNum;
    private TimeChangeReceiver timeChangeReceiver;
    private Context context;
    private List<UpPKGHelp.Passenger> passengerList;

    private transient long dayNum = 0;
    private transient long monthNum = 0;
    private transient long yearNum = 0;
    private transient long totalNum = 0;

    private long nowNum = 0;
    private long largeNum;

    private ImageView ivMsgIcon; // 馆内标识
    private TextView tvMsg; // 馆人满状态文字
    private GradientColorTextView gctv_title, gctv_subtitle1, gctv_subtitle2, gctv_subtitle3, gctv_subtitle4;
    SimpleNameValueBeanInterface defaultLanguageBean;
    private TextClock clockText;
    private UpPKGHelp upPKGHelp;

    /**
     * 定时器间隔时间
     */
    private transient long delayTime = 1 * 60 * 1000; // 1分钟测试方便点
    private transient long lastTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, this + " onCreate ");
        setContentView(R.layout.activity_main);
        context = this;
        upPKGHelp = new UpPKGHelp(context);

        lastTime = System.currentTimeMillis();

        largeNum = SPUtils.getLong(context, SPUtils.LARGENUM, 30);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        IntentFilter intentFilter = new IntentFilter();
        //intentFilter.addAction(Intent.ACTION_TIME_TICK);//每分钟变化
        intentFilter.addAction(Intent.ACTION_DATE_CHANGED);//每天变化
        //intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);//设置了系统时区
        //intentFilter.addAction(Intent.ACTION_TIME_CHANGED);//设置了系统时间

        timeChangeReceiver = new TimeChangeReceiver();
        registerReceiver(timeChangeReceiver, intentFilter);

        initView();
        initData();
        initServer();

    }


    private static Context updateResources(Context context, String language) {
        Resources resources = context.getResources();
        Locale locale = LanguageUtil.getSetLanguageLocale(context, language);
        Configuration configuration = resources.getConfiguration();

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
            configuration.locale = locale;
            //更新配置信息
        } else //如果 17 < = API < 25 Android 7.7.1
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1) {
                configuration.setLocale(locale);
                //更新配置信息
            } else {//API 25  Android 7.7.1
                configuration.setLocale(locale);
                configuration.setLocales(new LocaleList(locale));
            }

        return context.createConfigurationContext(configuration);
    }


    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(updateResources(newBase, SPUtils.getString(newBase, SPUtils.LAST_LANGUAGE_IDENTIFIER)));
    }

    /**
     * 初始化人数
     */
    private void initView() {

        ivMsgIcon = findViewById(R.id.iv_msg_icon);
        tvMsg = findViewById(R.id.tv_msg);
        tvTodayNum = findViewById(R.id.tv_today_num);
        tvMonthNum = findViewById(R.id.tv_month_num);
        tvYearNum = findViewById(R.id.tv_year_num);
        tvTotalNum = findViewById(R.id.tv_total_num);
        tvInNum = findViewById(R.id.tv_in_num);

        gctv_title = findViewById(R.id.gctv_title);
        gctv_subtitle1 = findViewById(R.id.gctv_subtitle1);
        gctv_subtitle2 = findViewById(R.id.gctv_subtitle2);
        gctv_subtitle3 = findViewById(R.id.gctv_subtitle3);
        gctv_subtitle4 = findViewById(R.id.gctv_subtitle4);
        clockText = findViewById(R.id.tv_time);
        findViewById(R.id.iv_setting).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSettingDialog();
            }
        });
        clockText.setTimeZone(getCurrentTimeZone());
        String string = SPUtils.getString(context, SPUtils.TITLE, LanguageUtil.getStringByLocale(context, R.string.app_name, null));
        String string1 = SPUtils.getString(context, SPUtils.SUBTITLE1, LanguageUtil.getStringByLocale(context, R.string.language_today_visitor_title, null));
        String string2 = SPUtils.getString(context, SPUtils.SUBTITLE2, LanguageUtil.getStringByLocale(context, R.string.language_month_visitor_title, null));
        String string3 = SPUtils.getString(context, SPUtils.SUBTITLE3, LanguageUtil.getStringByLocale(context, R.string.language_year_visitor_title, null));
        String string4 = SPUtils.getString(context, SPUtils.SUBTITLE4, LanguageUtil.getStringByLocale(context, R.string.language_histtory_visitor_title, null));


        initMainTitle(string, string1, string2, string3, string4);

        nowNum = SPUtils.getLong(context, SPUtils.INNUM_NOW, 0);
        if (nowNum < 0) {
            nowNum = 0;
        }
        changeAttention();
        tvInNum.setText(nowNum + SPUtils.getString(context, LanguageUtil.getStringByLocale(context, R.string.language_people_per, null)));

        passengerList = SPUtils.getPassengerList(context, SPUtils.PASSENGER);
        for (UpPKGHelp.Passenger passenger : passengerList) {
            String time = passenger.getTime();
            Short in = passenger.getIn();
            boolean isToday = DateUtil.isToday(time);
            boolean isMonth = DateUtil.isMonth(time);
            boolean isYear = DateUtil.isYear(time);
            if (isToday) {
                dayNum += in;
            }
            if (isMonth) {
                monthNum += in;
            }
            if (isYear) {
                yearNum += in;
            }
            totalNum += in;
        }
        tvTodayNum.setText(dayNum + SPUtils.getString(context, LanguageUtil.getStringByLocale(context, R.string.language_people_per, null)));
        tvMonthNum.setText(monthNum + SPUtils.getLong(context, SPUtils.INITMONTH, 0) + SPUtils.getString(context, LanguageUtil.getStringByLocale(context, R.string.language_people_per, null)));
        tvYearNum.setText(yearNum + SPUtils.getLong(context, SPUtils.INITYEAR, 0) + SPUtils.getString(context, LanguageUtil.getStringByLocale(context, R.string.language_people_per, null)));
        tvTotalNum.setText(totalNum + SPUtils.getLong(context, SPUtils.INITHISTORY, 0) + SPUtils.getString(context, LanguageUtil.getStringByLocale(context, R.string.language_people_per, null)));


        setDownLine(tvTodayNum);
        setDownLine(tvMonthNum);
        setDownLine(tvYearNum);
        setDownLine(tvTotalNum);
        setDownLine(tvInNum);
    }

    public String getCurrentTimeZone() {
        TimeZone tz = TimeZone.getDefault();
        String strTz = tz.getDisplayName(false, TimeZone.SHORT);
        return strTz;

    }

    private void changeAttention() {
        Log.i(TAG, "run:changeAttention 的时候 的实时数据是 " + nowNum);
        Log.i(TAG, "run:changeAttention largeNum 的时候 的实时数据是 " + largeNum);
        if (nowNum < largeNum) {
            tvMsg.setText(LanguageUtil.getStringByLocale(context, R.string.language_inner_idle_welcomt, null));
            ivMsgIcon.setImageResource(R.mipmap.ic_small_face);
            tvMsg.setTextColor(getResources().getColor(R.color.colorGreen));
        } else {
            tvMsg.setText(LanguageUtil.getStringByLocale(context, R.string.language_full_stop_enter, null));
            ivMsgIcon.setImageResource(R.mipmap.ic_attention);
            tvMsg.setTextColor(getResources().getColor(R.color.colorRed));

            mediaPlayer();
        }
    }

    MediaPlayer mMediaPlayer;

    private void mediaPlayer() {
        if (mMediaPlayer == null) {
            mMediaPlayer = MediaPlayer.create(this, R.raw.auido3);
        }
        if (mMediaPlayer.isPlaying()) {
            mMediaPlayer.seekTo(0);
        } else {
            mMediaPlayer.start();
        }
    }

    /**
     * 国际化下拉选项 ；以后增加语言就这这里添加
     *
     * @param spinner
     */
    private void initSpinerDataSource(Spinner spinner) {
        dataSource = new ArrayList<SimpleNameValueBeanInterface>();
        LanguageBean zh_cnBean = new LanguageBean(LanguageUtil.CHINESE_SIMPLE_IDENTIFIER, "简体中文");
        LanguageBean zh_twBean = new LanguageBean(LanguageUtil.CHINESE_TRADITIONAL_IDENTIFIER, "繁体中文");
        LanguageBean en_rgBean = new LanguageBean(LanguageUtil.ENGLISH_IDENTIFIER, "English");
        LanguageBean zh_jpBean = new LanguageBean(LanguageUtil.JAPANESE_IDENTIFIER, "Japanese");
        // 把上次选中的放第一个
        dataSource.add(zh_cnBean);
        dataSource.add(zh_twBean);
        dataSource.add(en_rgBean);
        dataSource.add(zh_jpBean);

        int index = 0;

        for (int i = 0; i < dataSource.size(); i++) {
            SimpleNameValueBeanInterface item = dataSource.get(i);
            if (item.getValue().equalsIgnoreCase(SPUtils.getString(context, SPUtils.LAST_LANGUAGE_IDENTIFIER))) {
                index = i;
            }
        }
        /*为spinner定义适配器，也就是将数据源存入adapter，这里需要三个参数
        1. 第一个是Context（当前上下文），这里就是this
        2. 第二个是spinner的布局样式，这里用android系统提供的一个样式
        3. 第三个就是spinner的数据源，这里就是dataList*/
        adapter = new SimpleNameValueAdapter(context, dataSource, android.R.layout.simple_spinner_item,
                R.layout.item_chosee);

        //为spinner绑定我们定义好的数据适配器
        spinner.setAdapter(adapter);
        adapter.notifyDataSetChanged();       //通知spinner刷新数据
        spinner.setSelection(index);
        defaultLanguageBean = dataSource.get(index);
        //为spinner绑定监听器，这里我们使用匿名内部类的方式实现监听器
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // 根据语言；先存储；再去更新当前界面的文字
                LanguageBean bean = (LanguageBean) adapter.getItem(position);
                SPUtils.putString(context, SPUtils.LAST_LANGUAGE_IDENTIFIER, bean.getValue());
                if (defaultLanguageBean.getValue().equalsIgnoreCase(bean.getValue())) {
                    return;
                } else {
                    defaultLanguageBean = bean;
                    toggleLanguage(bean.getValue());
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    /**
     * 静态文字等国际化的
     *
     * @param languageIdentifier
     */
    private void toggleLanguage(String languageIdentifier) {
        Resources res = LanguageUtil.toggleLanguage(context, languageIdentifier);// 先更新resource
        restartApplication();
    }

    private void restartApplication() {
        Intent intent = new Intent(context, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        android.os.Process.killProcess(android.os.Process.myPid());
    }


    /**
     * 设置最大可容纳人数
     */
    private void showSettingDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_seting_layout, null, false);
        builder.setView(view);
        dialog = builder.create();
        Window dialogWindow = dialog.getWindow();//获取window对象
        dialogWindow.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);//设置横向全屏
        dialogWindow.setBackgroundDrawable(new ColorDrawable(0));
        view.findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        /**
         * 用于国际化的相关标题
         */
        Spinner sp = view.findViewById(R.id.drop_down_spinner);
        initSpinerDataSource(sp);

        /**
         * 其他的业务相关的
         */
        final EditText etNum = view.findViewById(R.id.et_num);
        final EditText et_title = view.findViewById(R.id.et_title);
        final EditText et_sub_title1 = view.findViewById(R.id.et_sub_title1);
        final EditText et_sub_title2 = view.findViewById(R.id.et_sub_title2);
        final EditText et_sub_title3 = view.findViewById(R.id.et_sub_title3);
        final EditText et_sub_title4 = view.findViewById(R.id.et_sub_title4);
        final EditText et_init_month_num = view.findViewById(R.id.et_init_month_num);
        final EditText et_init_yearl_num = view.findViewById(R.id.et_init_yearl_num);
        final EditText et_init_history_num = view.findViewById(R.id.et_init_history_num);

        final EditText et_clearance_time = view.findViewById(R.id.et_clearance_time);  //清除时间

        etNum.setText(largeNum + "");
        etNum.setSelection(etNum.getText().length());
        String string = SPUtils.getString(context, SPUtils.TITLE, LanguageUtil.getStringByLocale(context, R.string.app_name, null));
        String string1 = SPUtils.getString(context, SPUtils.SUBTITLE1, LanguageUtil.getStringByLocale(context, R.string.language_today_visitor_title, null));
        String string2 = SPUtils.getString(context, SPUtils.SUBTITLE2, LanguageUtil.getStringByLocale(context, R.string.language_month_visitor_title, null));
        String string3 = SPUtils.getString(context, SPUtils.SUBTITLE3, LanguageUtil.getStringByLocale(context, R.string.language_year_visitor_title, null));
        String string4 = SPUtils.getString(context, SPUtils.SUBTITLE4, LanguageUtil.getStringByLocale(context, R.string.language_histtory_visitor_title, null));
        long initMouth = SPUtils.getLong(context, SPUtils.INITMONTH, 0);
        long initYear = SPUtils.getLong(context, SPUtils.INITYEAR, 0);
        long initHistory = SPUtils.getLong(context, SPUtils.INITHISTORY, 0);

        long clearance_time = SPUtils.getLong(context, SPUtils.CLEARANCE_TIME, 120);


        et_init_month_num.setText(initMouth + "");
        et_init_yearl_num.setText(initYear + "");
        et_init_history_num.setText(initHistory + "");

        //清除时间
        et_clearance_time.setText(clearance_time + "");

        et_title.setText(string);
        et_title.setSelection(string.length());
        et_sub_title1.setText(string1);
        et_sub_title2.setText(string2);
        et_sub_title3.setText(string3);
        et_sub_title4.setText(string4);
        view.findViewById(R.id.gtv_sure).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String trim = etNum.getText().toString().trim();
                String title = et_title.getText().toString().trim();
                String subTitle1 = et_sub_title1.getText().toString().trim();
                String subTitle2 = et_sub_title2.getText().toString().trim();
                String subTitle3 = et_sub_title3.getText().toString().trim();
                String subTitle4 = et_sub_title4.getText().toString().trim();
                String init_month_num = et_init_month_num.getText().toString().trim();
                String init_yearl_num = et_init_yearl_num.getText().toString().trim();
                String init_history_num = et_init_history_num.getText().toString().trim();
                String clearance_time = et_clearance_time.getText().toString().trim();

                if (TextUtils.isEmpty(clearance_time)) {
                    Toast.makeText(context, LanguageUtil.getStringByLocale(context, R.string.language_notice_please_input, null) + LanguageUtil.getStringByLocale(context, R.string.clearance_time, null), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(trim)) {
                    Toast.makeText(context, LanguageUtil.getStringByLocale(context, R.string.language_notice_please_input, null) + LanguageUtil.getStringByLocale(context, R.string.language_people_unit, null), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(title)) {
                    Toast.makeText(context, LanguageUtil.getStringByLocale(context, R.string.language_notice_please_input, null) + LanguageUtil.getStringByLocale(context, R.string.language_main_title, null), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(subTitle1)) {
                    Toast.makeText(context, LanguageUtil.getStringByLocale(context, R.string.language_notice_please_input, null) + LanguageUtil.getStringByLocale(context, R.string.language_today_visitor_title, null) + LanguageUtil.getStringByLocale(context, R.string.language_main_title, null), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(subTitle2)) {
                    Toast.makeText(context, LanguageUtil.getStringByLocale(context, R.string.language_notice_please_input, null) + LanguageUtil.getStringByLocale(context, R.string.language_month_visitor_title, null) + LanguageUtil.getStringByLocale(context, R.string.language_main_title, null), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(subTitle3)) {
                    Toast.makeText(context, LanguageUtil.getStringByLocale(context, R.string.language_notice_please_input, null) + LanguageUtil.getStringByLocale(context, R.string.language_year_visitor_title, null) + LanguageUtil.getStringByLocale(context, R.string.language_main_title, null), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(subTitle4)) {
                    Toast.makeText(context, LanguageUtil.getStringByLocale(context, R.string.language_notice_please_input, null) + LanguageUtil.getStringByLocale(context, R.string.language_histtory_visitor_title, null) + LanguageUtil.getStringByLocale(context, R.string.language_main_title, null), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(init_month_num)) {
                    Toast.makeText(context, LanguageUtil.getStringByLocale(context, R.string.language_notice_please_input, null) + LanguageUtil.getStringByLocale(context, R.string.language_month_init_title, null), Toast.LENGTH_SHORT).show();
                    return;
                }

                if (TextUtils.isEmpty(init_yearl_num)) {
                    Toast.makeText(context, LanguageUtil.getStringByLocale(context, R.string.language_notice_please_input, null) + LanguageUtil.getStringByLocale(context, R.string.language_year_init_title, null), Toast.LENGTH_SHORT).show();
                    return;
                }

                if (TextUtils.isEmpty(init_history_num)) {
                    Toast.makeText(context, LanguageUtil.getStringByLocale(context, R.string.language_notice_please_input, null) + LanguageUtil.getStringByLocale(context, R.string.language_history_init_title, null), Toast.LENGTH_SHORT).show();
                    return;
                }

                SPUtils.putString(context, SPUtils.TITLE, title);
                SPUtils.putString(context, SPUtils.SUBTITLE1, subTitle1);
                SPUtils.putString(context, SPUtils.SUBTITLE2, subTitle2);
                SPUtils.putString(context, SPUtils.SUBTITLE3, subTitle3);
                SPUtils.putString(context, SPUtils.SUBTITLE4, subTitle4);
                SPUtils.putLong(context, SPUtils.INITMONTH, Long.parseLong(init_month_num));
                SPUtils.putLong(context, SPUtils.INITYEAR, Long.parseLong(init_yearl_num));
                SPUtils.putLong(context, SPUtils.INITHISTORY, Long.parseLong(init_history_num));
                SPUtils.putLong(context, SPUtils.CLEARANCE_TIME, Long.parseLong(clearance_time));
                initMainTitle(title, subTitle1, subTitle2, subTitle3, subTitle4);

                long num = Long.parseLong(trim);
                SPUtils.putLong(context, SPUtils.LARGENUM, num);
                largeNum = num;
                changeAttention();
                Toast.makeText(context, LanguageUtil.getStringByLocale(context, R.string.language_setting_success, null), Toast.LENGTH_SHORT).show();
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    /**
     * 初始化主页标题
     *
     * @param title
     * @param subTitle1
     * @param subTitle2
     * @param subTitle3
     * @param subTitle4
     */
    private void initMainTitle(String title, String subTitle1, String subTitle2, String subTitle3, String subTitle4) {
        gctv_title.setText(title);
        gctv_subtitle1.setText(subTitle1);
        gctv_subtitle2.setText(subTitle2);
        gctv_subtitle3.setText(subTitle3);
        gctv_subtitle4.setText(subTitle4);

        long m = monthNum + SPUtils.getLong(context, SPUtils.INITMONTH, 0);
        tvMonthNum.setText(m + SPUtils.getString(context, LanguageUtil.getStringByLocale(context, R.string.language_people_per, null)));

        long y = yearNum + SPUtils.getLong(context, SPUtils.INITYEAR, 0);
        tvYearNum.setText(y + SPUtils.getString(context, LanguageUtil.getStringByLocale(context, R.string.language_people_per, null)));

        long h = totalNum + SPUtils.getLong(context, SPUtils.INITHISTORY, 0);
        tvTotalNum.setText(h + SPUtils.getString(context, LanguageUtil.getStringByLocale(context, R.string.language_people_per, null)));

    }

    private void setDownLine(TextView tv) {
        tv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        tv.getPaint().setAntiAlias(true);//抗锯齿
    }

    /**
     * 更新UI界面
     *
     * @param passengerItems
     */
    private void refreshUi(List<UpPKGHelp.PassengerItem> passengerItems) {
        for (int i = 0; i < passengerItems.size(); i++) {
            UpPKGHelp.PassengerItem passengerItem = passengerItems.get(i);
            //赋值最后一次上报时间
//            String str_date = passengerItem.getTime();
//            DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            Date date = new Date();
//            try {
//                date = formatter.parse(str_date);
//            } catch (Exception e) {
//                Log.d(TAG, "refreshUi: ", e);
//            }

            lastTime = System.currentTimeMillis();

            Short in = passengerItem.getIn();
            Short out = passengerItem.getOut();
            String time = passengerItem.getTime();

            nowNum = nowNum + in - out;
            if (nowNum < 1) {
                nowNum = 0;
            }
            Log.i(TAG, "run:tvInNum 的实时数据是 " + nowNum + " this:" + this + ",  view:" + tvInNum);
            if (in > 0) {
                dayNum += in;
                monthNum += in;
                yearNum += in;
                totalNum += in;
                UpPKGHelp.Passenger passenger = new UpPKGHelp.Passenger(in, time);
                passengerList.add(passenger);
            }
        }

        tvTodayNum.setText(dayNum + SPUtils.getString(context, LanguageUtil.getStringByLocale(context, R.string.language_people_per, null)));
        tvMonthNum.setText(monthNum + SPUtils.getLong(context, SPUtils.INITMONTH, 0) + SPUtils.getString(context, LanguageUtil.getStringByLocale(context, R.string.language_people_per, null)));
        tvYearNum.setText(yearNum + SPUtils.getLong(context, SPUtils.INITYEAR, 0) + SPUtils.getString(context, LanguageUtil.getStringByLocale(context, R.string.language_people_per, null)));
        tvTotalNum.setText(totalNum + SPUtils.getLong(context, SPUtils.INITHISTORY, 0) + SPUtils.getString(context, LanguageUtil.getStringByLocale(context, R.string.language_people_per, null)));
        Log.i(TAG, "run:refreshUi的时候 的实时数据是 " + nowNum + " thread:" + Thread.currentThread().getName());
        changeAttention();
        tvInNum.setText(nowNum + SPUtils.getString(context, LanguageUtil.getStringByLocale(context, R.string.language_people_per, null)));

        SPUtils.setPassengerList(context, SPUtils.PASSENGER, passengerList);
        SPUtils.putLong(context, SPUtils.INNUM_NOW, nowNum);
    }


    class TimeChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case Intent.ACTION_TIME_TICK:
                    //每过一分钟 触发
                    //Toast.makeText(context, "1 min passed", Toast.LENGTH_SHORT).show();
                    break;
                case Intent.ACTION_DATE_CHANGED:
                    //每过一天 触发
                    dayNum = 0;
                    tvTodayNum.setText(dayNum + SPUtils.getString(context, LanguageUtil.getStringByLocale(context, R.string.language_people_per, null)));  //每日访问数置为0
                    nowNum = 0;
                    SPUtils.putLong(context, SPUtils.INNUM_NOW, nowNum);//当前还在馆内人数置为0
                    tvInNum.setText(nowNum + SPUtils.getString(context, LanguageUtil.getStringByLocale(context, R.string.language_people_per, null)));
                    //Toast.makeText(context, "1 day passed", Toast.LENGTH_SHORT).show();
                    break;
                case Intent.ACTION_TIME_CHANGED:
                    //设置了系统时间
                    //Toast.makeText(context, "system time changed", Toast.LENGTH_SHORT).show();
                    break;
                case Intent.ACTION_TIMEZONE_CHANGED:
                    //设置了系统时区的action
                    //Toast.makeText(context, "system time zone changed", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }

    private void initData() {
        new DeviceWaitingSearch(this, "", "") {
            @Override
            public void onDeviceSearched(InetSocketAddress socketAddr) {
                Log.e(TAG, "onDeviceSearched: " + "已上线，搜索主机：" + socketAddr.getAddress().getHostAddress() + ":" + socketAddr.getPort());

            }
        }.start();
    }


    private ServerSocket serverSocket;
    private transient boolean isThreadRun;
    private AuthPKGHelp authPKGHelp = new AuthPKGHelp();

    private long authTime = -1;

    public class M6TcpClientThread extends Thread {
        private long heartTime = System.currentTimeMillis() / 1000;
        private Socket socket;

        public M6TcpClientThread(Socket socket) {
            this.socket = socket;
        }


        /**
         * 收到注册信息后，心跳轮询检测
         */
        private Runnable runHeartAble = new Runnable() {
            @Override
            public void run() {
                while (true) {
                    if (socket == null || socket.isClosed()) {
                        Log.i(TAG, "socket isClosed");
                        closeSocket();
                        break;
                    }
                    if ((System.currentTimeMillis() / 1000) - heartTime > 2 * 60) {
                        Log.i(TAG, "心跳超时 close socket");
                        closeSocket();
                        break;
                    }
                    try {
                        Thread.sleep(15000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        @Override
        public void run() {
            try {
                DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
                OutputStream os = socket.getOutputStream();
                DataOutputStream dataOutputStream = new DataOutputStream(os);
                isStartTimer = true;
                isThreadRun = true;
                Log.e(TAG, "run: 连接6090");
                while (isThreadRun) {
                    PKGBase baseReqData = new PKGBase();
                    byte[] head = baseReqData.readHead(dataInputStream);
                    byte funCode = baseReqData.readfunCode(dataInputStream);

                    switch (funCode) {
                        case 0X44:  //设备鉴权
                            Log.d(TAG, "M6客流设备鉴权成功 功能码：" + String.format("%02x", funCode));
                            AuthPKGHelp.AuthReqData authReqData = authPKGHelp.readReqData(head, funCode, dataInputStream);
                            authPKGHelp.sendData(head, os, 0 - 5 * 60 * 1000, authReqData.sn);
                            cachedThreadPool.execute(runHeartAble);
                            break;
                        case 0X43: //心跳
                            heartTime = System.currentTimeMillis() / 1000;
                            HeartPKGHelp mHeartPKGHelp = new HeartPKGHelp();
                            HeartPKGHelp.HeartReqData heartReqData = mHeartPKGHelp.readReqData(head, funCode, dataInputStream);
                            mHeartPKGHelp.sendData(head, os);
                            //发送Modbus上线通知
                            String m6Sn = new String(heartReqData.sn);
                            if (m6Sn.length() > 13) {
                                authPKGHelp.setOnline(true);
                                authPKGHelp.setM6Sn(m6Sn.substring(0, 13));
                                //GewuEventBus.getDefault().post(authPKGHelp);
                            }
                            Log.d(TAG, "run: heartTime:" + heartTime);
                            break;
                        case 0X42: //上报数据
                            if (timer == null) {
                                startTime();
                            }
                            UpPKGHelp.UpReqData upReqData = upPKGHelp.readReqData(head, funCode, dataInputStream);
                            upPKGHelp.sendData(head, os);
                            //GewuEventBus.getDefault().post(upReqData);
                            final List<UpPKGHelp.PassengerItem> passengerItems = upReqData.getmPassengerItem();
                            Log.e(TAG, "5555555555555555555run: " + passengerItems.toString());
                            if (passengerItems != null && passengerItems.size() > 0) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        refreshUi(passengerItems);
                                    }
                                });
                            }
                            break;
                        default:
                            break;
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public void closeSocket() {
            Log.i("11111", "close socket");
            try {
                if (socket != null) {
                    socket.close();
                }
                //发送Modbus离线通知
                authPKGHelp.setOnline(false);
            } catch (IOException e) {
            }
        }
    }

    public void startTime() {
        timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e(TAG, "run: TimerTask");
                        long nowTime = System.currentTimeMillis();
                        long min = SPUtils.getLong(context, SPUtils.CLEARANCE_TIME, 120);
                        if ((nowTime - lastTime) > min * 60 * 1000) {
                            Log.e(TAG, "run: TimerTask is clear");
                            lastTime = nowTime;
                            // TODO: 2020/11/11
                            nowNum = 0;
                            SPUtils.putLong(context, SPUtils.INNUM_NOW, nowNum);
                            tvInNum.setText(nowNum + SPUtils.getString(context, LanguageUtil.getStringByLocale(context, R.string.language_people_per, null)));
                            changeAttention();
                        }

                    }
                });

            }
        };
        timer.schedule(task, 0, delayTime);
    }

    private void initServer() {

        /**
         * 开启服务连接
         */
        new Thread() {
            public void run() {
                try {
                    serverSocket = new ServerSocket(DEVICE_FIND_PORT);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                while (true) {
                    try {
                        if (serverSocket != null) {
                            Socket socket = serverSocket.accept();
                            Thread thread = new M6TcpClientThread(socket);
                            thread.start();
                        }
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            }
        }.start();
    }


    private ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

    @Override
    protected void onPause() {
        super.onPause();
        Log.i(TAG, this + " onPause ");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, this + " onResume ");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, this + " onDestroy ");
        unregisterReceiver(timeChangeReceiver);

        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mMediaPlayer = null;
        }
        isThreadRun = false;
        Log.e(TAG, "isThreadRun: " + isThreadRun);
    }
}
